from wx import wx
import glob
import os
import AddSimulationDialog
import sqlite3
import base64
if wx.Platform == '__WXMSW__':
    from wx.lib.flashwin import FlashWindow


# will need to set a flag somehow to switch between win, linux and mac, if i want my app to be cross platform

class CreateSimulationTab(wx.Panel):
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        self.toolbar_ADDSIM = wx.NewId()
        self.toolbar_DELSIM = wx.NewId()
        self.toolbar_PLAYSIM = wx.NewId()
        self.toolbar_STOPSIM = wx.NewId()
        self.toolbar_UPDATESIM = wx.NewId()
        
        self.simFilePath = ""
        self.simulationListBox = wx.ListBox(self, -1, size=wx.Size(100, -1), style= wx.BORDER_SUNKEN | wx.LB_SINGLE | wx.LB_NEEDED_SB)
        
        box = wx.BoxSizer(wx.HORIZONTAL)

        label = wx.StaticText(self, -1, "Title:")
        label.SetHelpText("Tooltip that is displayed for the simulation.")
        box.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL)

        self.simTitleText = wx.TextCtrl(self, -1, "", size=(250,-1))
        self.simTitleText.SetHelpText("Enter Simulation Tooltip")
        box.Add(self.simTitleText, 1, wx.ALIGN_CENTRE|wx.ALL)

        box2 = wx.BoxSizer(wx.HORIZONTAL)

        label = wx.StaticText(self, -1, "Alternate Text:")
        label.SetHelpText("Alternative Text for Accessibility.")
        box2.Add(label, 0, wx.ALIGN_CENTRE|wx.ALL)

        self.simAltText = wx.TextCtrl(self, -1, "", size=(250,-1))
        self.simAltText.SetHelpText("Enter Textual Represent for the simulation.")
        box2.Add(self.simAltText, 1, wx.ALIGN_CENTRE|wx.ALL)
        
        self.simPanel = wx.Panel(self, style=wx.BORDER_SUNKEN)
        if wx.Platform == '__WXMSW__':
            self.simPlayer = FlashWindow(self.simPanel, style=wx.BORDER_NONE)
        else:
            self.simPlayer = wx.Panel(self.simPanel, style=wx.BORDER_SUNKEN)
        self.simToolbar = self.MakeSimulationToolbar()
        self.mainBox = wx.BoxSizer(wx.VERTICAL)
        self.botBox = wx.BoxSizer(wx.HORIZONTAL)
        self.topBox = wx.BoxSizer(wx.HORIZONTAL)
        self.horBox = wx.BoxSizer(wx.HORIZONTAL)
        self.verBox = wx.BoxSizer(wx.VERTICAL)
        self.horBox.Add(box, 0, wx.ALL | wx.ALIGN_LEFT)
        self.verBox.Add(self.horBox, 0, wx.ALL | wx.ALIGN_LEFT)
        self.verBox.Add(box2, 0, wx.ALL | wx.ALIGN_LEFT, 1)
        self.verBox.Add(self.simPanel, 1, wx.EXPAND, 1)
        self.topBox.Add(self.simToolbar, 1, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.botBox.Add(self.simulationListBox, 0, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.botBox.Add(self.verBox, 1, wx.EXPAND)
        self.mainBox.Add(self.topBox, 0, wx.ALL | wx.ALIGN_LEFT | wx.EXPAND)
        self.mainBox.Add(self.botBox, 1, wx.EXPAND)
        self.SetSizer(self.mainBox)

        wx.EVT_LISTBOX(self, self.simulationListBox.GetId(), self.OnSelectedSimItem)

    def MakeSimulationToolbar(self):
        tb = wx.ToolBar(self, -1, style=wx.TB_FLAT | wx.NO_BORDER)
        self.ToolBar = tb
        tb.AddTool(self.toolbar_ADDSIM, wx.Bitmap("images/list-add.png", wx.BITMAP_TYPE_PNG), isToggle=False, shortHelpString="Add Simulation")
        tb.AddTool(self.toolbar_DELSIM, wx.Bitmap("images/list-remove.png", wx.BITMAP_TYPE_PNG), shortHelpString="Remove Selected Simulation")
        tb.AddSeparator()
        tb.AddTool(self.toolbar_PLAYSIM, wx.Bitmap("images/media-playback-start.png", wx.BITMAP_TYPE_PNG), shortHelpString="Play Simulation")
        tb.AddTool(self.toolbar_STOPSIM, wx.Bitmap("images/media-playback-stop.png", wx.BITMAP_TYPE_PNG), shortHelpString="Stop Simulation")
        tb.AddSeparator()
        tb.AddTool(self.toolbar_UPDATESIM, wx.Bitmap("images/document-save.png", wx.BITMAP_TYPE_PNG), shortHelpString="Save Simulation Text")
        
        tb.EnableTool(self.toolbar_DELSIM, False)
        tb.EnableTool(self.toolbar_PLAYSIM, False)
        tb.EnableTool(self.toolbar_STOPSIM, False)
        tb.EnableTool(self.toolbar_UPDATESIM, False)
        
        wx.EVT_TOOL(self, self.toolbar_ADDSIM, self.AddSim)
        wx.EVT_TOOL(self, self.toolbar_DELSIM, self.DelSim)
        wx.EVT_TOOL(self, self.toolbar_PLAYSIM, self.PlaySim)
        wx.EVT_TOOL(self, self.toolbar_STOPSIM, self.StopSim)
        wx.EVT_TOOL(self, self.toolbar_UPDATESIM, self.UpdateSim)
        
        tb.Realize()
        
        return tb
    
    def OnSelectedSimItem(self, event):
        if(self.simulationListBox.GetSelection() != -1):
            delPath = self.TopLevelParent.GetAppPath() + "/tmpMedia.swf"
            tmpFileList = glob.glob(delPath)
            for tmpFile in tmpFileList:
                os.remove(tmpFile)
            
            self.simToolbar.EnableTool(self.toolbar_DELSIM, True)
            self.simToolbar.EnableTool(self.toolbar_PLAYSIM, True)
            self.simToolbar.EnableTool(self.toolbar_STOPSIM, True)
            self.simToolbar.EnableTool(self.toolbar_UPDATESIM, True)
            tmpString = self.simulationListBox.GetStringSelection()
            tmpId = int(tmpString.split(".", 1)[0])
            self.data = base64.decodestring(self.TopLevelParent.currentSimulationDict[tmpId][0])
            con = sqlite3.connect(self.TopLevelParent.database)
            cur = con.cursor()
            cur.execute("SELECT layout FROM ResourceTable WHERE resourceID = (?)", (tmpId,))
            for row in cur:
                tmpAltText = row[0].split("::")[0]
                tmpTitleText = row[0].split("::")[1]
            
            self.simAltText.SetValue(tmpAltText)
            self.simTitleText.SetValue(tmpTitleText)
            tmpSimFile = self.TopLevelParent.GetAppPath() + "/tmpMedia.swf"
            self.tmpFile = open(self.TopLevelParent.opj(tmpSimFile), "wb+")
            self.tmpFile.write(self.data)
            self.tmpFile.close()
            self.simPlayer.LoadMovie(0, tmpSimFile)
            self.simPlayer.SetSize(wx.Size(400, 300))
        
        self.TopLevelParent.DisplayDebug("select an item")
            
    def AddSim(self, event):
        self.TopLevelParent.DisplayDebug("add media")
        self.addSimDialog = AddSimulationDialog.AddSimulationDialog(self, -1, "Add Simulation to Course", size=(350, 200), style=wx.DEFAULT_DIALOG_STYLE)
        self.addSimDialog.CenterOnParent()
        
        if(self.addSimDialog.ShowModal() == wx.ID_OK):
            self.TopLevelParent.DisplayDebug("open flash and store and display")
            self.data = open(self.TopLevelParent.opj(self.addSimDialog.simFileText.GetValue()), "rb").read()
            self.layoutValue = self.addSimDialog.simAltText.GetValue() + "::" + self.addSimDialog.simTitleText.GetValue()
            con = sqlite3.connect(self.TopLevelParent.database)
            cur = con.cursor()
            cur.execute("INSERT INTO ResourceTable(resourceTypeID, layout, resourceData, courseID) VALUES(5, ?, ?, ?)", (self.layoutValue, base64.encodestring(sqlite3.Binary(self.data)), self.TopLevelParent.currentCourseID))
            lastID = cur.lastrowid
            con.commit()
            con.close()
            self.TopLevelParent.currentSimulationDict = self.TopLevelParent.RefreshListBox(self.simulationListBox, self.TopLevelParent.currentCourseID, 5, None)
            self.simPlayer.LoadMovie(0, self.addSimDialog.simFileText.GetValue())
            self.simPlayer.SetSize(wx.Size(400, 300))
            self.simAltText.SetValue(self.addSimDialog.simAltText.GetValue())
            self.simTitleText.SetValue(self.addSimDialog.simTitleText.GetValue())
            self.simulationListBox.SetSelection(self.simulationListBox.FindString(str(lastID) + ". " + self.addSimDialog.simTitleText.GetValue()))
        
        self.addSimDialog.Destroy()

    def DelSim(self, event):
        tmpString = self.simulationListBox.GetStringSelection()
        tmpId = int(tmpString.split(".", 1)[0])
        con = sqlite3.connect(self.TopLevelParent.database)
        cur = con.cursor()
        cur.execute("DELETE FROM ResourceTable WHERE resourceID = (?)", (tmpId,))
        con.commit()
        con.close()
        self.TopLevelParent.currentSimulationDict = self.TopLevelParent.RefreshListBox(self.simulationListBox, self.TopLevelParent.currentCourseID, 5, None)
        delPath = self.TopLevelParent.GetAppPath() + "/tmpMedia.swf"
        tmpFileList = glob.glob(delPath)
        for tmpFile in tmpFileList:
            os.remove(tmpFile)

        self.TopLevelParent.DisplayDebug("del")

    def UpdateSim(self, event):
        tmpString = self.simulationListBox.GetStringSelection()
        tmpId = int(tmpString.split(".", 1)[0])
        self.layoutValue = self.simAltText.GetValue() + "::" + self.simTitleText.GetValue()
        con = sqlite3.connect(self.TopLevelParent.database)
        cur = con.cursor()
        cur.execute("UPDATE ResourceTable set layout = (?) where resourceID = (?)", (self.layoutValue, tmpId))
        con.commit()
        con.close()
        self.TopLevelParent.currentSimulationDict = self.TopLevelParent.RefreshListBox(self.simulationListBox, self.TopLevelParent.currentCourseID, 5, None)
        delPath = self.TopLevelParent.GetAppPath() + "/tmpMedia.swf"
        tmpFileList = glob.glob(delPath)
        for tmpFile in tmpFileList:
            os.remove(tmpFile)
        
        self.data = base64.decodestring(self.TopLevelParent.currentSimulationDict[tmpId][0])
        tmpSimFile = self.TopLevelParent.GetAppPath() + "/tmpMedia.swf"
        self.tmpFile = open(self.TopLevelParent.opj(tmpSimFile), "wb+")
        self.tmpFile.write(self.data)
        self.tmpFile.close()
        self.simPlayer.LoadMovie(0, tmpSimFile)
        self.simulationListBox.SetSelection(self.simulationListBox.FindString(str(tmpId) + ". " + self.simTitleText.GetValue()))
        self.TopLevelParent.DisplayDebug("update sim")
        
    def PlaySim(self, event):
        self.simPlayer.Play()
        self.TopLevelParent.DisplayDebug("play sim")
    
    def StopSim(self, event):
        self.simPlayer.Stop()
        self.TopLevelParent.DisplayDebug("stop sim")
